package com.bruip.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.bruip.reggie.common.BaseResponse;
import com.bruip.reggie.util.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 王若龙
 * @date 2022-10-05 09:20
 */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String requestURI = request.getRequestURI();

        log.info("拦截到路径：{}", requestURI);

        //配置不需要拦截的url
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/favicon.ico",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //判断当前请求是否需要拦截
        boolean b = checkUrl(urls, requestURI);

        //不需要拦截的路径，直接放行
        if (b) {
            filterChain.doFilter(request, response);
            return;
        }

        //判断管理端是否登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        Long userId = (Long) request.getSession().getAttribute("user");
        if (empId !=  null || userId !=null ) {
            log.info("用户以登陆，用户id为：{}", empId);
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }

        //判断移动端登录逻辑
      /*  if (userId != null) {
            log.info("用户以登陆，用户id为：{}", userId);
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }*/

        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(BaseResponse.error("NOTLOGIN")));
    }

    /**
     * 检验请求路径的方法
     *
     * @param urls
     * @param requestUrl
     * @return boolean
     */
    public boolean checkUrl(String[] urls, String requestUrl) {
        for (String url : urls) {
            boolean b = ANT_PATH_MATCHER.match(url, requestUrl);
            if (b) {
                log.info("放行路径：{}", requestUrl);
                return true;
            }
        }
        return false;
    }
}
